# apps/app01/views/cart_views.py

from rest_framework import views, status
from rest_framework.response import Response
# from rest_framework.permissions import IsAuthenticated  # 如果需要登录校验可启用

from apps.app01.models import Cart, User
from apps.app01.views.cart_delete.serializers import CartRemoveSerializer


class RemoveCartItemView(views.APIView):


    def delete(self, request):
        # 1. 反序列化并校验请求数据
        serializer = CartRemoveSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {
                    "code": 0,
                    "message": "参数错误",
                    "errors": serializer.errors
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2. 获取当前用户
        user_id = request.user['user_id']
        user = User.objects.get(id=user_id)
        # user = User.objects.first()  # 测试时可写死

        # if user.is_anonymous:
        #     return Response(
        #         {"code": 0, "message": "用户未登录"},
        #         status=status.HTTP_401_UNAUTHORIZED
        #     )

        # 3. 获取要删除的商品 ID
        product_id = serializer.validated_data["productId"]

        # 4. 在购物车中删除该用户对应 product_id 的所有商品
        deleted_count, _ = Cart.objects.filter(user=user_id, product_id=product_id).delete()

        if deleted_count == 0:
            # 表示没有找到任何记录可删除
            return Response(
                {"code": 0, "message": "购物车中无此商品或商品已被删除"},
                status=status.HTTP_404_NOT_FOUND
            )

        # 5. 返回删除成功的响应
        return Response(
            {"code": 1, "message": "ok"},
            status=status.HTTP_200_OK
        )
